Pillow模組提供一個ImageDraw模組,可以繪出點、線、矩形、橢圓、多邊形
想繪製一個點,語法為
point([(x1,y1),...(xn,yn)], fill) #fill可以設定顏色
(x,y)是想畫出的點座標,fill可以是RGBA()或是直接指定顏色
如果想繪製線條的話,語法為
line([(x1,y1),...(xn,yn)], width, fill) #width為寬度預設值都會給1
範例
from PIL import Image, ImageDraw
newImage = Image.new('RGBA', (300, 300), "Yellow")
drawObj = ImageDraw.Draw(newImage)
for x in range(100, 200, 3):
for y in range(100, 200, 3)
drawObj.point([(x,y)], fill = 'Green')
drawObj.line([(0,0),(299,0),(299,299), (0,299), (0,0)], fill = "Black")
for x in range(150, 300, 10):
drawObj.line([(x,0), (300, x-150)], fill = "Blue")
for y in range(150, 300, 10):
drawObj.line([(0,y), (y-150, 300)], fill = "Blue")
newImage.save("drawpic.png")
那圓和橢圓的部分可以用ellipse()繪製,語法為
ellipse((left,top,right,bottom), fill, outline) #outline為外框顏色
矩形部分可以用rectangle()繪製,語法為
rectangle((left,top,right,bottom), fill, outline)
多邊形可以用polygon()繪製,語法為
polygon([(x1,y1),...,(xn,yn)], fill, outline)
from PIL import Image, ImageDraw
newImage = Image.new('RGBA', (300, 300), 'Yellow')
drawObj = ImageDraw.Draw(newImage)
drawObj.rectangle((0,0,299,299), outline = 'Black')
drawObj.ellipse((30,60,130,100), outline = 'Black')
drawObj.ellipse((65,65,95,95), fill = 'Blue')
drawObj.ellipse((170,60,270,100), outline = 'Black')
drawObj.ellipse((205,65,235,95), fill = 'Blue')
drawObj.polygon([(150,120), (180,180), (120,180), (150,120)], fill = 'Aqua')
drawObj.rectangle((100,210,200,240), fill = 'Red')
newImage.save("drapic.png")
是不是很簡單,以前不知道這麼多功能可以用,現在發現這其實很方便,大家也可以嘗試畫看看想畫的圖